import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useSettingsStore = defineStore('settings', () => {
  // 应用设置
  const appSettings = ref({
    theme: 'light', // light, dark, auto
    language: 'zh-CN',
    autoSave: true,
    autoSaveInterval: 30000, // 30秒
    maxUndoSteps: 50,
    maxRedoSteps: 50,
    showWelcomeScreen: true,
    enableAnalytics: false,
    enableCrashReporting: false
  })

  // 编辑器设置
  const editorSettings = ref({
    gridSize: 20,
    snapToGrid: true,
    snapToObjects: true,
    snapThreshold: 10,
    showGrid: true,
    showRulers: true,
    showGuides: true,
    showDimensions: true,
    showLabels: true,
    enableSnapLines: true,
    enableSmartGuides: true,
    enableAutoAlign: true,
    enableAutoDistribute: true
  })

  // 性能设置
  const performanceSettings = ref({
    renderQuality: 'high', // low, medium, high
    enableHardwareAcceleration: true,
    enableVSync: true,
    maxFPS: 60,
    enableObjectPooling: true,
    enableLazyLoading: true,
    enableCulling: true,
    cullingThreshold: 1000,
    enableCompression: true
  })

  // 快捷键设置
  const keyboardSettings = ref({
    shortcuts: {
      'undo': { key: 'Ctrl+Z', enabled: true },
      'redo': { key: 'Ctrl+Y', enabled: true },
      'save': { key: 'Ctrl+S', enabled: true },
      'saveAs': { key: 'Ctrl+Shift+S', enabled: true },
      'open': { key: 'Ctrl+O', enabled: true },
      'new': { key: 'Ctrl+N', enabled: true },
      'copy': { key: 'Ctrl+C', enabled: true },
      'paste': { key: 'Ctrl+V', enabled: true },
      'cut': { key: 'Ctrl+X', enabled: true },
      'delete': { key: 'Delete', enabled: true },
      'selectAll': { key: 'Ctrl+A', enabled: true },
      'deselect': { key: 'Escape', enabled: true },
      'zoomIn': { key: 'Ctrl+=', enabled: true },
      'zoomOut': { key: 'Ctrl+-', enabled: true },
      'resetZoom': { key: 'Ctrl+0', enabled: true },
      'fitToScreen': { key: 'Ctrl+Shift+F', enabled: true },
      'toggleGrid': { key: 'Ctrl+G', enabled: true },
      'toggleRulers': { key: 'Ctrl+R', enabled: true },
      'toggleGuides': { key: 'Ctrl+Shift+G', enabled: true },
      'group': { key: 'Ctrl+G', enabled: true },
      'ungroup': { key: 'Ctrl+Shift+G', enabled: true },
      'lock': { key: 'Ctrl+L', enabled: true },
      'unlock': { key: 'Ctrl+Shift+L', enabled: true },
      'hide': { key: 'Ctrl+H', enabled: true },
      'show': { key: 'Ctrl+Shift+H', enabled: true },
      'bringToFront': { key: 'Ctrl+Shift+]', enabled: true },
      'sendToBack': { key: 'Ctrl+Shift+[', enabled: true },
      'alignLeft': { key: 'Ctrl+Shift+L', enabled: true },
      'alignCenter': { key: 'Ctrl+Shift+C', enabled: true },
      'alignRight': { key: 'Ctrl+Shift+R', enabled: true },
      'alignTop': { key: 'Ctrl+Shift+T', enabled: true },
      'alignMiddle': { key: 'Ctrl+Shift+M', enabled: true },
      'alignBottom': { key: 'Ctrl+Shift+B', enabled: true }
    },
    enableKeyboardShortcuts: true,
    enableContextMenu: true,
    enableTooltips: true
  })

  // 导出设置
  const exportSettings = ref({
    defaultFormat: 'png', // png, jpg, svg, pdf
    defaultQuality: 90,
    defaultResolution: 300, // DPI
    includeBackground: true,
    includeGrid: false,
    includeGuides: false,
    includeAnnotations: true,
    defaultSize: 'original', // original, custom, fit
    customWidth: 1920,
    customHeight: 1080,
    enableTransparency: true,
    enableCompression: true
  })

  // 导入设置
  const importSettings = ref({
    defaultUnit: 'cm', // cm, m, mm, inch
    defaultScale: 1,
    enableAutoResize: true,
    enableAutoCenter: true,
    enableLayerPreservation: true,
    enableMetadataPreservation: true,
    enableColorPreservation: true,
    enableTexturePreservation: true,
    maxFileSize: 50 * 1024 * 1024, // 50MB
    allowedFormats: ['jpg', 'jpeg', 'png', 'svg', 'pdf', 'dxf', 'dwg']
  })

  // 计算属性
  const isDarkTheme = computed(() => {
    if (appSettings.value.theme === 'auto') {
      return window.matchMedia('(prefers-color-scheme: dark)').matches
    }
    return appSettings.value.theme === 'dark'
  })

  const isLightTheme = computed(() => {
    if (appSettings.value.theme === 'auto') {
      return window.matchMedia('(prefers-color-scheme: light)').matches
    }
    return appSettings.value.theme === 'light'
  })

  const effectiveGridSize = computed(() => {
    return editorSettings.value.showGrid ? editorSettings.value.gridSize : 0
  })

  const canUndo = computed(() => {
    return appSettings.value.maxUndoSteps > 0
  })

  const canRedo = computed(() => {
    return appSettings.value.maxRedoSteps > 0
  })

  // Actions
  const updateAppSettings = (updates) => {
    appSettings.value = { ...appSettings.value, ...updates }
    saveSettings()
  }

  const updateEditorSettings = (updates) => {
    editorSettings.value = { ...editorSettings.value, ...updates }
    saveSettings()
  }

  const updatePerformanceSettings = (updates) => {
    performanceSettings.value = { ...performanceSettings.value, ...updates }
    saveSettings()
  }

  const updateKeyboardSettings = (updates) => {
    keyboardSettings.value = { ...keyboardSettings.value, ...updates }
    saveSettings()
  }

  const updateExportSettings = (updates) => {
    exportSettings.value = { ...exportSettings.value, ...updates }
    saveSettings()
  }

  const updateImportSettings = (updates) => {
    importSettings.value = { ...importSettings.value, ...updates }
    saveSettings()
  }

  const setTheme = (theme) => {
    appSettings.value.theme = theme
    applyTheme(theme)
    saveSettings()
  }

  const setLanguage = (language) => {
    appSettings.value.language = language
    applyLanguage(language)
    saveSettings()
  }

  const toggleAutoSave = () => {
    appSettings.value.autoSave = !appSettings.value.autoSave
    saveSettings()
  }

  const setAutoSaveInterval = (interval) => {
    appSettings.value.autoSaveInterval = Math.max(5000, Math.min(300000, interval))
    saveSettings()
  }

  const setMaxUndoSteps = (steps) => {
    appSettings.value.maxUndoSteps = Math.max(0, Math.min(1000, steps))
    saveSettings()
  }

  const setMaxRedoSteps = (steps) => {
    appSettings.value.maxRedoSteps = Math.max(0, Math.min(1000, steps))
    saveSettings()
  }

  const toggleGrid = () => {
    editorSettings.value.showGrid = !editorSettings.value.showGrid
    saveSettings()
  }

  const toggleRulers = () => {
    editorSettings.value.showRulers = !editorSettings.value.showRulers
    saveSettings()
  }

  const toggleGuides = () => {
    editorSettings.value.showGuides = !editorSettings.value.showGuides
    saveSettings()
  }

  const setGridSize = (size) => {
    editorSettings.value.gridSize = Math.max(1, Math.min(100, size))
    saveSettings()
  }

  const toggleSnapToGrid = () => {
    editorSettings.value.snapToGrid = !editorSettings.value.snapToGrid
    saveSettings()
  }

  const toggleSnapToObjects = () => {
    editorSettings.value.snapToObjects = !editorSettings.value.snapToObjects
    saveSettings()
  }

  const setSnapThreshold = (threshold) => {
    editorSettings.value.snapThreshold = Math.max(1, Math.min(50, threshold))
    saveSettings()
  }

  const setRenderQuality = (quality) => {
    performanceSettings.value.renderQuality = quality
    applyRenderQuality(quality)
    saveSettings()
  }

  const toggleHardwareAcceleration = () => {
    performanceSettings.value.enableHardwareAcceleration = !performanceSettings.value.enableHardwareAcceleration
    applyHardwareAcceleration()
    saveSettings()
  }

  const setMaxFPS = (fps) => {
    performanceSettings.value.maxFPS = Math.max(30, Math.min(120, fps))
    saveSettings()
  }

  const updateShortcut = (action, key) => {
    if (keyboardSettings.value.shortcuts[action]) {
      keyboardSettings.value.shortcuts[action].key = key
      saveSettings()
    }
  }

  const toggleShortcut = (action) => {
    if (keyboardSettings.value.shortcuts[action]) {
      keyboardSettings.value.shortcuts[action].enabled = !keyboardSettings.value.shortcuts[action].enabled
      saveSettings()
    }
  }

  const resetShortcuts = () => {
    keyboardSettings.value.shortcuts = {
      'undo': { key: 'Ctrl+Z', enabled: true },
      'redo': { key: 'Ctrl+Y', enabled: true },
      'save': { key: 'Ctrl+S', enabled: true },
      'saveAs': { key: 'Ctrl+Shift+S', enabled: true },
      'open': { key: 'Ctrl+O', enabled: true },
      'new': { key: 'Ctrl+N', enabled: true },
      'copy': { key: 'Ctrl+C', enabled: true },
      'paste': { key: 'Ctrl+V', enabled: true },
      'cut': { key: 'Ctrl+X', enabled: true },
      'delete': { key: 'Delete', enabled: true },
      'selectAll': { key: 'Ctrl+A', enabled: true },
      'deselect': { key: 'Escape', enabled: true },
      'zoomIn': { key: 'Ctrl+=', enabled: true },
      'zoomOut': { key: 'Ctrl+-', enabled: true },
      'resetZoom': { key: 'Ctrl+0', enabled: true },
      'fitToScreen': { key: 'Ctrl+Shift+F', enabled: true },
      'toggleGrid': { key: 'Ctrl+G', enabled: true },
      'toggleRulers': { key: 'Ctrl+R', enabled: true },
      'toggleGuides': { key: 'Ctrl+Shift+G', enabled: true },
      'group': { key: 'Ctrl+G', enabled: true },
      'ungroup': { key: 'Ctrl+Shift+G', enabled: true },
      'lock': { key: 'Ctrl+L', enabled: true },
      'unlock': { key: 'Ctrl+Shift+L', enabled: true },
      'hide': { key: 'Ctrl+H', enabled: true },
      'show': { key: 'Ctrl+Shift+H', enabled: true },
      'bringToFront': { key: 'Ctrl+Shift+]', enabled: true },
      'sendToBack': { key: 'Ctrl+Shift+[', enabled: true },
      'alignLeft': { key: 'Ctrl+Shift+L', enabled: true },
      'alignCenter': { key: 'Ctrl+Shift+C', enabled: true },
      'alignRight': { key: 'Ctrl+Shift+R', enabled: true },
      'alignTop': { key: 'Ctrl+Shift+T', enabled: true },
      'alignMiddle': { key: 'Ctrl+Shift+M', enabled: true },
      'alignBottom': { key: 'Ctrl+Shift+B', enabled: true }
    }
    saveSettings()
  }

  const getShortcut = (action) => {
    return keyboardSettings.value.shortcuts[action]?.key || ''
  }

  const isShortcutEnabled = (action) => {
    return keyboardSettings.value.shortcuts[action]?.enabled || false
  }

  const setDefaultExportFormat = (format) => {
    exportSettings.value.defaultFormat = format
    saveSettings()
  }

  const setDefaultExportQuality = (quality) => {
    exportSettings.value.defaultQuality = Math.max(1, Math.min(100, quality))
    saveSettings()
  }

  const setDefaultExportResolution = (resolution) => {
    exportSettings.value.defaultResolution = Math.max(72, Math.min(600, resolution))
    saveSettings()
  }

  const setDefaultImportUnit = (unit) => {
    importSettings.value.defaultUnit = unit
    saveSettings()
  }

  const setDefaultImportScale = (scale) => {
    importSettings.value.defaultScale = Math.max(0.1, Math.min(10, scale))
    saveSettings()
  }

  const setMaxImportFileSize = (size) => {
    importSettings.value.maxFileSize = Math.max(1024 * 1024, Math.min(100 * 1024 * 1024, size))
    saveSettings()
  }

  // 应用设置
  const applyTheme = (theme) => {
    const root = document.documentElement
    if (theme === 'dark' || (theme === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
      root.classList.add('dark')
    } else {
      root.classList.remove('dark')
    }
  }

  const applyLanguage = (language) => {
    // 应用语言设置
    document.documentElement.lang = language
    // 这里可以加载对应的语言包
  }

  const applyRenderQuality = (quality) => {
    // 应用渲染质量设置
    const canvas = document.querySelector('canvas')
    if (canvas) {
      const ctx = canvas.getContext('2d')
      if (ctx) {
        switch (quality) {
          case 'low':
            ctx.imageSmoothingEnabled = false
            break
          case 'medium':
            ctx.imageSmoothingEnabled = true
            ctx.imageSmoothingQuality = 'medium'
            break
          case 'high':
            ctx.imageSmoothingEnabled = true
            ctx.imageSmoothingQuality = 'high'
            break
        }
      }
    }
  }

  const applyHardwareAcceleration = () => {
    // 应用硬件加速设置
    const canvas = document.querySelector('canvas')
    if (canvas) {
      if (performanceSettings.value.enableHardwareAcceleration) {
        canvas.style.transform = 'translateZ(0)'
      } else {
        canvas.style.transform = ''
      }
    }
  }

  // 保存和加载设置
  const saveSettings = () => {
    const settings = {
      app: appSettings.value,
      editor: editorSettings.value,
      performance: performanceSettings.value,
      keyboard: keyboardSettings.value,
      export: exportSettings.value,
      import: importSettings.value,
      timestamp: Date.now()
    }
    
    localStorage.setItem('designer-settings', JSON.stringify(settings))
  }

  const loadSettings = () => {
    const saved = localStorage.getItem('designer-settings')
    if (saved) {
      try {
        const settings = JSON.parse(saved)
        
        if (settings.app) appSettings.value = { ...appSettings.value, ...settings.app }
        if (settings.editor) editorSettings.value = { ...editorSettings.value, ...settings.editor }
        if (settings.performance) performanceSettings.value = { ...performanceSettings.value, ...settings.performance }
        if (settings.keyboard) keyboardSettings.value = { ...keyboardSettings.value, ...settings.keyboard }
        if (settings.export) exportSettings.value = { ...exportSettings.value, ...settings.export }
        if (settings.import) importSettings.value = { ...importSettings.value, ...settings.import }
        
        // 应用设置
        applyTheme(appSettings.value.theme)
        applyLanguage(appSettings.value.language)
        applyRenderQuality(performanceSettings.value.renderQuality)
        applyHardwareAcceleration()
        
      } catch (error) {
        console.error('加载设置失败:', error)
      }
    }
  }

  const resetSettings = () => {
    // 重置所有设置为默认值
    appSettings.value = {
      theme: 'light',
      language: 'zh-CN',
      autoSave: true,
      autoSaveInterval: 30000,
      maxUndoSteps: 50,
      maxRedoSteps: 50,
      showWelcomeScreen: true,
      enableAnalytics: false,
      enableCrashReporting: false
    }
    
    editorSettings.value = {
      gridSize: 20,
      snapToGrid: true,
      snapToObjects: true,
      snapThreshold: 10,
      showGrid: true,
      showRulers: true,
      showGuides: true,
      showDimensions: true,
      showLabels: true,
      enableSnapLines: true,
      enableSmartGuides: true,
      enableAutoAlign: true,
      enableAutoDistribute: true
    }
    
    performanceSettings.value = {
      renderQuality: 'high',
      enableHardwareAcceleration: true,
      enableVSync: true,
      maxFPS: 60,
      enableObjectPooling: true,
      enableLazyLoading: true,
      enableCulling: true,
      cullingThreshold: 1000,
      enableCompression: true
    }
    
    resetShortcuts()
    
    exportSettings.value = {
      defaultFormat: 'png',
      defaultQuality: 90,
      defaultResolution: 300,
      includeBackground: true,
      includeGrid: false,
      includeGuides: false,
      includeAnnotations: true,
      defaultSize: 'original',
      customWidth: 1920,
      customHeight: 1080,
      enableTransparency: true,
      enableCompression: true
    }
    
    importSettings.value = {
      defaultUnit: 'cm',
      defaultScale: 1,
      enableAutoResize: true,
      enableAutoCenter: true,
      enableLayerPreservation: true,
      enableMetadataPreservation: true,
      enableColorPreservation: true,
      enableTexturePreservation: true,
      maxFileSize: 50 * 1024 * 1024,
      allowedFormats: ['jpg', 'jpeg', 'png', 'svg', 'pdf', 'dxf', 'dwg']
    }
    
    saveSettings()
  }

  const exportSettingsFun = () => {
    return {
      app: appSettings.value,
      editor: editorSettings.value,
      performance: performanceSettings.value,
      keyboard: keyboardSettings.value,
      export: exportSettings.value,
      import: importSettings.value,
      exportTime: Date.now()
    }
  }

  const importSettingsFun = (data) => {
    if (data.app) appSettings.value = { ...appSettings.value, ...data.app }
    if (data.editor) editorSettings.value = { ...editorSettings.value, ...data.editor }
    if (data.performance) performanceSettings.value = { ...performanceSettings.value, ...data.performance }
    if (data.keyboard) keyboardSettings.value = { ...keyboardSettings.value, ...data.keyboard }
    if (data.export) exportSettings.value = { ...exportSettings.value, ...data.export }
    if (data.import) importSettings.value = { ...importSettings.value, ...data.import }
    
    saveSettings()
  }

  // 初始化
  const initialize = () => {
    loadSettings()
  }

  return {
    // 状态
    appSettings,
    editorSettings,
    performanceSettings,
    keyboardSettings,
    exportSettings,
    importSettings,
    
    // 计算属性
    isDarkTheme,
    isLightTheme,
    effectiveGridSize,
    canUndo,
    canRedo,
    
    // Actions
    updateAppSettings,
    updateEditorSettings,
    updatePerformanceSettings,
    updateKeyboardSettings,
    updateExportSettings,
    updateImportSettings,
    setTheme,
    setLanguage,
    toggleAutoSave,
    setAutoSaveInterval,
    setMaxUndoSteps,
    setMaxRedoSteps,
    toggleGrid,
    toggleRulers,
    toggleGuides,
    setGridSize,
    toggleSnapToGrid,
    toggleSnapToObjects,
    setSnapThreshold,
    setRenderQuality,
    toggleHardwareAcceleration,
    setMaxFPS,
    updateShortcut,
    toggleShortcut,
    resetShortcuts,
    getShortcut,
    isShortcutEnabled,
    setDefaultExportFormat,
    setDefaultExportQuality,
    setDefaultExportResolution,
    setDefaultImportUnit,
    setDefaultImportScale,
    setMaxImportFileSize,
    saveSettings,
    loadSettings,
    resetSettings,
    exportSettingsFun,
    importSettingsFun,
    initialize
  }
})
